package com.bbx.androidapi.net;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;

import com.bbx.androidapi.util.DebugUtil;
import com.bbx.androidapi.util.SystemUtil;
import com.bbx.androidapi.util.ToastUtil;

public class BbxBaseNetwork {

	private static final String METHOD_GET = "GET";

	private static final String AUTH_KEY = "Authorization";

	private Context context;

	private String url;

	private boolean isShowErr;

	/**
	 * 初始化
	 * 
	 * @param ctx
	 * @param url
	 *            url地址
	 * @param isShowErr
	 *            是否在网络错误时弹出Toast提示用户
	 */
	public BbxBaseNetwork(Context ctx, String url, boolean isShowErr) {
		this.url = url;
		context = ctx;
		this.isShowErr = isShowErr;
	}

	/**
	 * 通过GET方式从服务器取得数据（有auth验证）
	 * 
	 * @param auth_key
	 *            http auth验证码
	 * @return
	 */
	protected InputStream getWebContent(String auth_key) {
		try {
			URL url = new URL(this.url);
			DebugUtil.printDebugInfo("url--->" + this.url);
			HttpURLConnection conn = null;
			conn = checkNetType(url, conn, context);
			conn.setRequestProperty(AUTH_KEY, auth_key);
			conn.setRequestMethod(METHOD_GET);
			conn.setConnectTimeout(20 * 1000);
			DebugUtil.printDebugInfo("responeCode:" + conn.getResponseCode());
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return conn.getInputStream();
			} else {
				if (isShowErr)
					showErr();
			}
		} catch (Exception e) {
			if (isShowErr)
				showErr();
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过GET方式从服务器取得数据（无Auth验证）
	 * 
	 * @return
	 */
	protected InputStream getWebWithoutAuth() {
		try {
			URL url = new URL(this.url);
			HttpURLConnection conn = null;
			conn = checkNetType(url, conn, context);
			conn.setRequestMethod(METHOD_GET);
			conn.setConnectTimeout(60 * 1000);
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return conn.getInputStream();
			}
		} catch (Exception e) {
			showErr();
			e.printStackTrace();
		}
		return null;
	}

	private void showErr() {
		try {
			((Activity) context).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					ToastUtil.showToast(context, "网络错误");
				}
			});
		} catch (ClassCastException s) {
			s.printStackTrace();
		}
	}

	/**
	 * 通过POST方式从服务器获取数据 有返回
	 * 
	 * @param params
	 *            封装好的请求参数
	 * @param urlPath
	 *            地址
	 * @return
	 */
	protected InputStream getContentWithPOST(List<NameValuePair> params) {
		// 建立POST连接
		HttpPost httpRequest = new HttpPost(url.toString());
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			int response = httpResponse.getStatusLine().getStatusCode();
			DebugUtil.printDebugInfo("发送错误请求responseCode:" + response);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				InputStream in = new ByteArrayInputStream(strResult.getBytes());
				return in;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过POST方式向服务器发送数据 无返回
	 * 
	 * @param params
	 *            封装好的请求参数
	 * @param url
	 *            地址
	 * @param isErr
	 *            是否为异常错误的时候调用
	 */
	protected void sendInfo(String url, List<NameValuePair> params,
			boolean isErr) {
		/* 建立HTTPost对象 */
		HttpPost httpRequest = new HttpPost(url);
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
			// 请求超时
			if (isErr)
				defaultHttpClient.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 2500);
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = defaultHttpClient.execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				// 测试服务器返回值
				DebugUtil.printDebugInfo("send = " + strResult);
			} else {
				DebugUtil.printDebugInfo("运行记录返回httpcode:"
						+ httpResponse.getStatusLine().getStatusCode());
			}
		} catch (ClientProtocolException e) {
			// tv.setText(e.getMessage().toString());
			e.printStackTrace();
		} catch (IOException e) {
			// tv.setText(e.getMessage().toString());
			e.printStackTrace();
		} catch (Exception e) {
			// tv.setText(e.getMessage().toString());
			e.printStackTrace();
		}
	}

	/**
	 * 根据网络类型建立连接
	 * 
	 * @param url
	 * @param conn
	 * @return
	 * @throws IOException
	 */
	private HttpURLConnection checkNetType(URL url, HttpURLConnection conn,
			Context context) throws IOException {
		if (SystemUtil.isMobileActive(context)) { // 手机网络
			String proxyHost = android.net.Proxy.getDefaultHost();

			if (proxyHost == null) { // net方式
				conn = (HttpURLConnection) url.openConnection();
			} else {// wap方式
				int proxyPort = android.net.Proxy.getDefaultPort();
				Proxy proxy = null;

				proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
						proxyHost, proxyPort));
				if (proxy != null) {
					conn = (HttpURLConnection) url.openConnection(proxy);
				}
			}
		} else { // wifi网络
			conn = (HttpURLConnection) url.openConnection();
		}
		return conn;
	}
}
